package com.ruoyi.system.async;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.baidu.aip.util.Base64Util;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.Requests;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 优待证查询工具类
 * @Author Nuanyang
 * @Data 2023/5/27 10:30
 */
@Slf4j
@Component
public class UnemployedCardUtil {

    /**
     *  获取验证码请求地址
     * @author NuanYang
     * @date 2023/5/27 10:34
     */
    private static final String verificationCodeUrl = "https://ecard.mva.gov.cn:18443/cert/pc/api/common/getCheckCode";

    /**
     * 查询优待证符合资格Url
     * @author NuanYang
     * @date 2023/5/27 10:34
     */
    private static final String searchUrl = "https://ecard.mva.gov.cn:18443/cert/pc/api/apply/qualificationCheck";

    public Boolean searchCourtesyCardByNameAndidCard(String name,String idCardNumber){
        String res = HttpUtil.get(verificationCodeUrl);
        JSONObject jsonObject = new JSONObject(res);
        JSONObject json = new JSONObject(jsonObject.get("data"));
        JSONObject object = new JSONObject();
        object.put("sessionId",json.get("sessionId"));
        object.put("name",name);
        object.put("idCardNumber",idCardNumber);
        // TODO 图片解析
        String s = this.generalBasic(Base64.getDecoder().decode(String.valueOf(json.get("base64")).substring(String.valueOf(json.get("base64")).indexOf(",") + 1)));
        object.put("code",s);
        Map headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        String resp = Requests.post(searchUrl).headers(headers).jsonBody(object).connectTimeout(1000*60).send().readToText();
        JSONObject respJson = new JSONObject(resp);
        JSONObject rjson = new JSONObject(respJson.get("data"));
        if(ObjectUtil.isEmpty(rjson.get("provinceCode"))){
            log.error("校验优待证符合条件结果,姓名:"+name+";结果：false");
            return false;
        }else{
            log.info("校验优待证符合条件结果,姓名:"+name+";结果：true");
            return  true;
        }

    }

    /**
     * 百度ocr token 30天默认有效期：24.11c5a0994f976fa8715e21bd05cc04da.2592000.1687759442.282335-34051246
     * @author NuanYang
     * @date 2023/5/27 13:58
     */
    private String getToken(){
        String url = "https://aip.baidubce.com/oauth/2.0/token";
        String clientId = "8OsMLvk8774mkdCI34kMyKCG";
        String clientSecret = "fEsai71SgajkGc1o9u3mPezHvz6fgyVr";
        String grantType = "client_credentials";

        String response = HttpUtil.createPost(url)
                .form("client_id", clientId)
                .form("client_secret", clientSecret)
                .form("grant_type", grantType)
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .execute()
                .body();
        JSONObject jsonObject = new JSONObject(response);
        Object access_token = jsonObject.get("access_token");
        return String.valueOf(access_token);
    }

    /**
     * ocr接口验证嘛解析
     *
     * @param imgData 图片byte
     * @return
     */
    public String generalBasic(byte[] imgData) {
//        //云网
//        String url = "http://api.jfbym.com/api/YmServer/customApi";
//        try {
//            BASE64Encoder encoder = new BASE64Encoder();
//            String encodeStr = encoder.encode(imgData);
//            Map headers = new HashMap<>();
//            headers.put("Content-Type", "application/json");
//            String verify_type;
//            verify_type = "10103";
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("image", encodeStr);
//            jsonObject.put("type", verify_type);
//            jsonObject.put("token", "dXxMc9ejsCBnkjUcmHhCiY6XhFdDhBzBI-6uEjjFEio");
//            String resp = Requests.post(url).headers(headers).jsonBody(jsonObject).connectTimeout(1000*60).send().readToText();
//            JSONObject jsonObject1 = JSONObject.parseObject(resp);
//            JSONObject jsonObject2 = jsonObject1.getJSONObject("data");
//            String data = jsonObject2.getString("data");
//            return data;
//        } catch (Exception e) {
//            log.error("获取云网验证码接口超时");
//        }
//        return null;
        //百度
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        try {
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam + "&language_type=ENG"+"&detect_direction=true";
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.11c5a0994f976fa8715e21bd05cc04da.2592000.1687759442.282335-34051246";
            String result = com.ruoyi.system.async.HttpUtil.post(url, accessToken, param);
            com.alibaba.fastjson2.JSONObject jsonObject = com.alibaba.fastjson2.JSONObject.parseObject(result);
            JSONArray wordsResult = jsonObject.getJSONArray("words_result");
            com.alibaba.fastjson2.JSONObject wordsResultJSONObject = wordsResult.getJSONObject(0);
            return wordsResultJSONObject.getString("words");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
